<template>
    <div class="card-list">
    <div v-for="(item,index) in categoryData" :key="index">
        <Data :title="item.title" :num="item.num"></Data>
    </div>
  </div>

  <div class="shaixuan">
    <div class="shaixuan-content">
        <el-input
              v-model="searchKeyword"
              placeholder="请输入搜索关键词"
              style="width:200px;"
              clearable
              :prefix-icon="Search"
            >
        </el-input>
        <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @clear="handleClear"
            />
            <el-button
              type="primary"
              @click="handleSearch"
            >
              <el-icon><Search /></el-icon>搜索
            </el-button>
            <el-button
              type="success"
              @click="handleAdd"
            >
              <el-icon><Plus /></el-icon>新增
            </el-button>
    </div>
  </div>

  <div class="table">
    <el-table :data="JSON.parse(JSON.stringify(fillData)).splice((PageNo-1)*PageSize,PageSize)" border stripe>
        <el-table-column prop="category_id" label="标签ID" width="100" />
        <el-table-column prop="category_name" label="标签名称" />
        <el-table-column prop="category_createtime" label="创建时间" >
            <template #default="scope">
              <span>{{ formatTimestamp(scope.row.category_createtime) }}</span>
            </template>
        </el-table-column>
        <el-table-column prop="category_level" label="级别" >
            <template #default="scope">
              <span>{{ scope.row.category_level==1?'一级标签':scope.row.category_level==2?'二级标签':'三级标签' }}</span>
            </template>
        </el-table-column>
        <el-table-column prop="is_delete" label="状态" >
            <template #default="scope">
              <span>{{ scope.row.is_delete==0?'正常':'封禁' }}</span>
            </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
                <template #default="scope">
                  <el-button
                    type="primary"
                    size="small"
                    @click="handleEdit(scope.row)"
                    >编辑</el-button
                  >
                </template>
        </el-table-column>
    </el-table>
    <div class="pagination">
        <el-pagination
              v-model:current-page="PageNo"
              v-model:page-size="PageSize"
              :total="fillData.length"
              :page-sizes="[10, 20, 30, 50]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handlePageNoChange"
            />
    </div>
  </div>

  <el-dialog v-model="editshow" title="编辑" width="300px">
    <div class="edit-item">
        <span>标签名称:</span>
        <el-input style="width: 200px;" v-model="edit.category_name"/>
    </div>
    <div class="edit-item">
        <span>标签状态:</span>
        <el-select style="width: 200px;"
            v-model="edit.is_delete"
          >
            <el-option
              label="正常"
              :value="0"
            />
            <el-option
              label="封禁"
              :value="1"
            />
          </el-select>
    </div>
    <div v-if="edit.category_level!==1" class="edit-item">
        <span>标签上属:</span>
        <el-select style="width: 200px;"
            v-model="edit.category_order"
          >
            <el-option
              v-for="(item,index) in orderoptions"
              :label="item.label"
              :value="item.value"
              :key="index"
            />
          </el-select>
    </div>
    <template #footer>
        <span>
          <el-button @click="editshow = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleEditSubmit"
            >确定</el-button
          >
        </span>
      </template>
  </el-dialog>

  <el-dialog @close="clearadd" v-model="addshow" title="编辑" width="300px">
    <div class="add-item">
        <span>标签名称:</span>
        <el-input style="width: 200px;" v-model="add.category_name"/>
    </div>
    <div class="add-item">
        <span>标签级别:</span>
        <el-select @change="add.category_order=null" style="width: 200px;"
            v-model="add.category_level"
          >
            <el-option
              label="一级标签"
              :value="1"
            />
            <el-option
              label="二级标签"
              :value="2"
            />
            <el-option
              label="三级标签"
              :value="3"
            />
          </el-select>
    </div>
    <div v-if="add.category_level!==1" class="add-item">
        <span>标签上属:</span>
        <el-select style="width: 200px;"
            v-model="add.category_order"
          >
            <el-option
              v-for="(item,index) in orderoptions1"
              :label="item.label"
              :value="item.value"
              :key="index"
            />
          </el-select>
    </div>
    <template #footer>
        <span>
          <el-button @click="addshow = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleaddSubmit"
            >确定</el-button
          >
        </span>
      </template>
  </el-dialog>
  </template>
  
  <script lang="ts" setup>
  import {ref,reactive,onBeforeMount,computed} from 'vue'
  import { Search,Plus} from '@element-plus/icons-vue'
  import { ElMessage } from 'element-plus'
  import Data from './Data.vue';
  import {GetCategorys,GetCategoryData,AddCategory,UpdateCategory} from '@/service/api/category'
  let PageNo=ref(1)
  let PageSize=ref(10)
  let fillData=ref([])
  let edit=ref({})
  let add=ref({
    category_name:'',
    category_level:1,
    category_order:null,
  })
  let addshow=ref(false)
  let editshow=ref(false)
let searchKeyword=ref('')
let dateRange=ref([])
let tableData=ref([])
  const orderoptions = computed(() => {
  const arr = tableData.value; // 简化后续访问
  
  // 空值保护
  if (!arr || !Array.isArray(arr)) return [];

  const getLevelOptions = (targetLevel) => {
    const options = [];
    
    // 处理二级分类逻辑
    if (targetLevel === 2) {
      options.push(
        ...arr
          .filter(item => item.category_level === 1&&item.category_id!==1)
          .map(item => ({
            value: item.category_id,
            label: item.category_name
          }))
      );
    }
    // 处理三级分类逻辑
    else if (targetLevel === 3) {
      // 先构建一级分类映射表
      const level1Map = new Map(
        arr
          .filter(item => item.category_level === 1)
          .map(item => [item.category_id, item.category_name])
      );

      // 过滤二级分类并构建层级标签
      options.push(
        ...arr
          .filter(item => 
            item.category_level === 2 &&
            level1Map.has(item.category_order)
          )
          .map(item => ({
            value: item.category_id,
            label: `${level1Map.get(item.category_order)}/${item.category_name}`
          }))
      );
    }

    return options;
  };

  // 执行对应层级的处理逻辑
  return getLevelOptions(edit.value.category_level);
});
const orderoptions1 = computed(() => {
  const arr = tableData.value; // 简化后续访问
  
  // 空值保护
  if (!arr || !Array.isArray(arr)) return [];

  const getLevelOptions = (targetLevel) => {
    const options = [];
    
    // 处理二级分类逻辑
    if (targetLevel === 2) {
      options.push(
        ...arr
          .filter(item => item.category_level === 1&&item.category_id!==1)
          .map(item => ({
            value: item.category_id,
            label: item.category_name
          }))
      );
    }
    // 处理三级分类逻辑
    else if (targetLevel === 3) {
      // 先构建一级分类映射表
      const level1Map = new Map(
        arr
          .filter(item => item.category_level === 1)
          .map(item => [item.category_id, item.category_name])
      );

      // 过滤二级分类并构建层级标签
      options.push(
        ...arr
          .filter(item => 
            item.category_level === 2 &&
            level1Map.has(item.category_order)
          )
          .map(item => ({
            value: item.category_id,
            label: `${level1Map.get(item.category_order)}/${item.category_name}`
          }))
      );
    }

    return options;
  };

  // 执行对应层级的处理逻辑
  return getLevelOptions(add.value.category_level);
});

  let categoryData=reactive([
    {
        title:'标签总数',
        num:'0'
    },
    {
        title:'本月新增',
        num:'0'
    },
    {
        title:'使用最多',
        num:'0'
    },
    {
        title:'壁纸最多',
        num:'0'
    }
])

onBeforeMount(()=>{
    getcategorys()
    getcategorydata()
})

function clearadd(){
  add.value={
    category_name:'',
    category_level:1,
    category_order:null,
  }
}

function handleaddSubmit(){
  if(add.value.category_name==='')return ElMessage.error('请输入标签名称')
  if(!add.value.category_order&&add.value.category_level!==1)return ElMessage.error('请选择标签上属')
  AddCategory({
    category_name:add.value.category_name,
    category_level:add.value.category_level,
    category_order:add.value.category_order
  }).then(res=>{
    if(res.data.code==200){
      ElMessage.success('添加成功')
      getcategorydata()
      getcategorys()
      clearadd()
      addshow.value=false
    }
  })
}
function handleAdd(){
  addshow.value=true
}
function handleEditSubmit(){
  UpdateCategory({
    category_name:edit.value.category_name,
    category_id:edit.value.category_id,
    category_order:edit.value.category_order,
    is_delete:edit.value.is_delete
  }).then(res=>{
    if(res.data.code==200){
      ElMessage.success('修改成功')
      getcategorydata()
      getcategorys()
     editshow.value=false
    }
  })
}
function handleEdit(item){
    edit.value=JSON.parse(JSON.stringify(item))
    editshow.value=true
}
function handleSizeChange(value){
    PageSize.value=value
}

function handlePageNoChange(value){
    PageNo.value=value
}
function handleClear(){
    dateRange.value=[]
}
function handleSearch(){
  fillData.value=tableData.value.filter(item=>{
      return item.category_name.includes(searchKeyword.value)
  })
  fillData.value=fillData.value.filter(item=>{
      return item.category_createtime>=(dateRange.value[0]?new Date(dateRange.value[0]).getTime():item.category_createtime)&&item.category_createtime<=(dateRange.value[1]?new Date(dateRange.value[1]).getTime():item.category_createtime)
  })
  PageNo.value=1
}
function getcategorys(){
    GetCategorys().then(res=>{
        if(res.data.code==200){
          fillData.value=res.data.data
            tableData.value=res.data.data
        }
    })
}
function getcategorydata(){
    GetCategoryData().then(res=>{
        if(res.data.code==200){
            categoryData[0].num=res.data.data.all
            categoryData[1].num=res.data.data.new
            categoryData[2].num=res.data.data.hot
            categoryData[3].num=res.data.data.max
       }
    })
}
  function formatTimestamp(timestamp) {
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hours = date.getHours()
  const minutes = date.getMinutes()
  const formattedMonth = month < 10 ? '0' + month : month
  const formattedDay = day < 10 ? '0' + day : day
  const formattedHours = hours < 10 ? '0' + hours : hours
  const formattedMinutes = minutes < 10 ? '0' + minutes : minutes
 
  return `${year}-${formattedMonth}-${formattedDay} ${formattedHours}:${formattedMinutes}`
}
  </script>
  
  <style lang="scss" scoped>
@import url("@/assets/css/view.scss");
</style>
  